import React, { useState, useEffect, useRef, useImperativeHandle } from 'react';
import {
    Form,
    Button,
    Input,
    Affix,
    Select,
    message,
    Space,
    Switch,
    Drawer,
    Row,
    Col,
    InputNumber,
    Spin,
    Empty,
    TimePicker,
    DatePicker,
} from 'antd';
import cmdbres from '@/data/cmdbres';
import request from '@/utils/request';
import regexpUtil from '@/utils/regexpUtil';
import hcpUtils from '@/utils/hcpUtils';

const { uniqueIdentificationRegexp, commonTextRegexp } = regexpUtil;
const ModelFormItem = ({ form, cRef, cmModuleId }) => {
    const [formItemData, setFormItemData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [dealData, setDealData] = useState([]);

    const queryTableHeaders = async () => {
        try {
            setLoading(true);
            const res = await request({
                ...cmdbres.queryTableHeader,
                params: {
                    cm_module_id: cmModuleId,
                },
            });
            setLoading(false);
            if (res && res.code == 200) {
                let arr = [];
                let dealArr = [];
                res.data?.fields?.filter((field, index) => {
                    if (!['cm_appkey', 'cm_name'].includes(field.propertyKey)) {
                        arr.push(field);
                    }
                    if (['date', 'datetime'].includes(field.propertyType)) {
                        const formString = field.propertyType == 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss';
                        dealArr.push({
                            propertyKey: field.propertyKey,
                            fn: (obj) => {
                                obj[field.propertyKey] = obj[field.propertyKey]?.format(formString);
                            },
                        });
                    }
                }); //过滤"数据来源"字段
                setFormItemData(arr);
                setDealData(dealArr);
            }
        } catch (error) {
            console.log('queryTableHeaders -> error', error);
        }
    };

    //目前支持数字、文本、下拉框，默认为文本
    const renderFormItem = (field, index) => {
        const { propertyType, propertyName, propertyKey, woIsRequired, woIsUnique, propertyEnumValue } = field;
        switch (propertyType) {
            case 'number':
            case 'float': {
                return (
                    <Form.Item
                        key={index}
                        label={propertyName}
                        name={propertyKey}
                        rules={[
                            { required: woIsRequired == 1, message: `请输入${propertyName}` }, //必填
                        ]}
                    >
                        <InputNumber style={{ width: '50%', marginRight: 10 }} />
                    </Form.Item>
                );
            }
            case 'enum': {
                let enumValueStr = propertyEnumValue.replace(/'/g, '"');
                const enums = JSON.parse(propertyEnumValue);
                console.log(JSON.parse(enumValueStr), enums);
                return (
                    <Form.Item
                        key={index}
                        label={propertyName}
                        name={propertyKey}
                        rules={[
                            { required: woIsRequired == 1, message: `请选择${propertyName}` }, //必填
                        ]}
                    >
                        <Select placeholder="请选择" style={{ width: '50%', marginRight: 10 }} showSearch>
                            {Object.keys(enums).map((item, index) => (
                                <Select.Option key={index} value={item}>
                                    {enums[item]}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                );
            }
            case 'date': {
                return (
                    <Form.Item
                        key={index}
                        label={propertyName}
                        name={propertyKey}
                        rules={[
                            { required: woIsRequired == 1, message: `请选择` }, //必填
                        ]}
                    >
                        <DatePicker placeholder="请选择日期" style={{ width: '50%' }} />
                    </Form.Item>
                );
            }
            case 'datetime': {
                return (
                    <Form.Item
                        key={index}
                        label={propertyName}
                        name={propertyKey}
                        rules={[
                            { required: woIsRequired == 1, message: `请选择` }, //必填
                        ]}
                    >
                        <DatePicker showTime placeholder="请选择时间" style={{ width: '50%' }} />
                    </Form.Item>
                );
            }
            default: {
                return (
                    <Form.Item
                        key={index}
                        label={propertyName}
                        name={propertyKey}
                        rules={[
                            { required: woIsRequired == 1, message: `请输入${propertyName}` }, //必填
                            commonTextRegexp(0, 256), //暂时最大输入为256，后期可以在新增属性页面扩展输入长度字段
                        ]}
                    >
                        <Input placeholder={`请输入${propertyName}`} maxLength={256} />
                    </Form.Item>
                );
            }
        }
    };

    useImperativeHandle(cRef, () => ({
        dealDataFn: async (fieldsValue) => {
            dealData.map((item) => {
                item.fn(fieldsValue);
            });
        },
    }));

    useEffect(() => {
        if (cmModuleId) queryTableHeaders();
    }, [cmModuleId]);

    return (
        <>
            {loading ? (
                <Spin />
            ) : formItemData && formItemData.length ? (
                formItemData.map((field, index) => renderFormItem(field, index))
            ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
        </>
    );
};

export default ModelFormItem;
